package org.satellite13.discountpack.client.android;

import java.util.Random;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class AccountListActivity extends Activity {
	private int requestCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.account_list);
	}

	@Override
	protected void onResume() {
		super.onResume();
		AccountManager accountManager = AccountManager
				.get(getApplicationContext());
		Account[] accounts = accountManager.getAccountsByType("com.google");
		if (accounts.length == 0) {
			Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
			requestCode = new Random().nextInt();
			startActivityForResult(intent, requestCode);
		} else {
			RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
			rg.removeAllViews();
			for (final Account account : accounts) {
				final RadioButton rb = new RadioButton(this);
				rb.setText(account.name);
				rb.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						Intent ret = new Intent();
						ret.putExtra("account", account);						
						setResult(RESULT_OK, ret);
						finish();
						return;
					}
				});
				rg.addView(rb);
			}
		}
	}

	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		setResult(RESULT_CANCELED);
		return;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (this.requestCode == requestCode) {
			if (resultCode == RESULT_CANCELED) {
				setResult(RESULT_CANCELED);
				finish();
				return;
			}
		}
	}
}
